//
//  MessageViewController.m
//  ShangPiBao
//
//  Created by chirui on 2017/10/16.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "MessageViewController.h"
#import "LeftMessageTableViewCell.h"
#import "RightMessageTableViewCell.h"
#import "CompanyMainDetailsVController.h"

@interface MessageViewController ()<UITableViewDelegate,UITableViewDataSource> {
    
    UITableView * _tableView;
    
    NSString * typeStr;
    UIButton * leftBtn;
    UIButton * rightBtn;
    
    UIView * lineView_one;
    UIView * lineView_two;
    
    NSMutableArray * _dataArray;
    int _page;
    int _totailPage;
    NSString * buyOrSellStr;

}

@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    typeStr = @"1";
    buyOrSellStr= @"2";
    _page =1;
    _dataArray = @[].mutableCopy;
    TitleView(@"消息");
    self.view.backgroundColor =[UIColor whiteColor];
    [self creatTableView];
    
    [self getDataForRequestForType:buyOrSellStr];
}

-(void)creatTableView {
    
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64-48) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    UIView * view =[[UIView alloc]init];
    _tableView.tableFooterView = view;
    [self.view addSubview:_tableView];
    
        MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
   
           _page = 1;
            [self getDataForRequestForType:buyOrSellStr];
   
       }];
        _tableView.mj_header = header;
   
       MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
           _page++;
           [self getDataForRequestForType:buyOrSellStr];
        }];
    
        footer.automaticallyRefresh = YES;
        _tableView.mj_footer =footer;
       _tableView.mj_footer.hidden = YES;
    
    [_tableView registerNib:[UINib nibWithNibName:[LeftMessageTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[LeftMessageTableViewCell reuseIdentifier]];
    
    [_tableView registerNib:[UINib nibWithNibName:[RightMessageTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[RightMessageTableViewCell reuseIdentifier]];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataArray.count;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([typeStr isEqualToString:@"1"]) {
        return 300;
    }else {
        return 140;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 60;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([typeStr isEqualToString:@"1"]) {
        
        NSDictionary * dic = _dataArray[indexPath.row];
        
        LeftMessageTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[LeftMessageTableViewCell reuseIdentifier] forIndexPath:indexPath];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
         _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [cell.companyIcon sd_setImageWithURL:ImageUrl(dic[@"uca"]) placeholderImage:ImageName(@"img_home_newest")];
        cell.companyBtn.tag = 100+indexPath.row;
        [cell.companyBtn addTarget:self action:@selector(companyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
         [cell.bigImage sd_setImageWithURL:ImageUrl(dic[@"ppicture"]) placeholderImage:ImageName(@"img_home_newest")];
        [cell.bigImage tapAction:^{
            
            NSArray * imageArray = @[dic[@"ppicture"]];
            
            XHPicView *picView = [[XHPicView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) withImgs:nil withImgUrl:imageArray];
            picView.eventBlock = ^(NSString *event){
                NSLog(@"触发事件%@",event);
            };
            UIWindow *window = [[UIApplication sharedApplication].delegate window];
            
            [window addSubview:picView];
            
            
//            TCLPhotoBrowserViewController *photo = [[TCLPhotoBrowserViewController alloc]init];
//            photo.photos = imageArray;
//            photo.currentPage = 1;
//            [self presentViewController:photo animated:YES completion:nil];
        }];
        
        cell.companyName.text = dic[@"ucn"];
        cell.details.text = dic[@"pcontent"];
        cell.details.frame = CGRectMake(10, 80, WIDTH -20, 20);
       cell.details.numberOfLines = 2;
        [cell.details sizeToFit];

        cell.timeLabel.text = dic[@"ptime"];
        return cell;
    }else {
        NSDictionary * dic = _dataArray[indexPath.row];
        
        
       RightMessageTableViewCell  * cell = [tableView dequeueReusableCellWithIdentifier:[RightMessageTableViewCell reuseIdentifier] forIndexPath:indexPath];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.goodsName.text = [NSString stringWithFormat:@"求购产品:%@",dic[@"ptitle"]];
        cell.goodsNumber.text = [NSString stringWithFormat:@"求购数量:%@",dic[@"pnum"]];
        cell.guigeLabel.text = [NSString stringWithFormat:@"求购规格:%@",dic[@"psm"]];
        cell.phoneLabel.text = [NSString stringWithFormat:@"电话：%@",dic[@"utel"]];
        
        [cell.phoneLabel tapAction:^{
            
            NSString * phoneStr = dic[@"utel"];
            
            [self callPhoneRequestFor:phoneStr];
        }];
        cell.timeLabel.text = dic[@"ptime"];
        
       return cell;
    }
}

-(void)companyBtnClick:(UIButton *)btn{

    NSDictionary * dic = _dataArray[btn.tag - 100];
    
    CompanyMainDetailsVController * company =[[CompanyMainDetailsVController alloc]init];
    company.companyId = dic[@"uid"];
    company.companyNameStr = dic[@"ucn"];
    company.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:company animated:YES];

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPat{

    [tableView deselectRowAtIndexPath:indexPat animated:YES];
    
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView * heardView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 60)];
    heardView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UIView * topView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 50)];
    
    topView.backgroundColor =[UIColor whiteColor];
    [heardView addSubview:topView];
    
    lineView_one =[[UIView alloc]initWithFrame:CGRectMake(20, 48, WIDTH/2-40, 2)];
    lineView_one.backgroundColor = GoldTextColor;
    lineView_one.hidden = YES;
    [topView addSubview:lineView_one];
    
    lineView_two =[[UIView alloc]initWithFrame:CGRectMake(WIDTH/2+20, 48, WIDTH/2-40, 2)];
    lineView_two.backgroundColor = GoldTextColor;
    lineView_two.hidden = YES;
    [topView addSubview:lineView_two];
    
    leftBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    leftBtn.frame = CGRectMake(0, 0, WIDTH/2, 48);
    [leftBtn setTitle:@"供应信息" forState:UIControlStateNormal];
    
    leftBtn.titleLabel.font =[UIFont systemFontOfSize:16];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:leftBtn];
    
    rightBtn =[UIButton buttonWithType:UIButtonTypeSystem];
    rightBtn.frame = CGRectMake(WIDTH/2, 0, WIDTH/2, 48);
    [rightBtn setTitle:@"求购信息" forState:UIControlStateNormal];
    if ([typeStr isEqualToString:@"1"]) {
        [leftBtn setTitleColor:GoldTextColor forState:UIControlStateNormal];
        [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        lineView_one.hidden = NO;
        lineView_two.hidden = YES;
        
    }else {
        
        [rightBtn setTitleColor:GoldTextColor forState:UIControlStateNormal];
        [leftBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        lineView_one.hidden = YES;
        lineView_two.hidden = NO;
    }
    
    rightBtn.titleLabel.font =[UIFont systemFontOfSize:16];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:rightBtn];
    
    return heardView;
}

-(void)leftBtnClick:(UIButton *)btn {
    
    typeStr=@"1";
    buyOrSellStr = @"2";
    [_tableView registerNib:[UINib nibWithNibName:[LeftMessageTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[LeftMessageTableViewCell reuseIdentifier]];
    _page = 1;
    [self getDataForRequestForType:buyOrSellStr];
}

-(void)rightBtnClick:(UIButton *)btn {
    
     buyOrSellStr = @"1";
    typeStr=@"2";
    [_tableView registerNib:[UINib nibWithNibName:[RightMessageTableViewCell reuseIdentifier] bundle:nil] forCellReuseIdentifier:[RightMessageTableViewCell reuseIdentifier]];
    
    _page = 1;
    [self getDataForRequestForType:buyOrSellStr];
}


-(void)getDataForRequestForType:(NSString *)type{
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_tableView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@?uphone=%@&ver=%@&pclass=0&page=%d&ustatus=%@",address_url,get_messageList_api,USER_DEFAULTGet(@"phone"),md5ver,_page,type];
    
   // NSString *encoded = [parametersStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"parametersStr = %@",parametersStr);
    //    SHuiMBhubNoTimeLoding;
    [PostNetWorking netWorkingStr:parametersStr  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"err"] intValue]==0) {
            
            _totailPage = [responseObject[@"maxpage"] intValue];
            
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"data"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"data"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"data"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"data"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (_dataArray.count>10) {
                    
                    _tableView.mj_footer.hidden = NO;
                }else {
                    _tableView.mj_footer.hidden = YES;
                    
                }
                [_tableView.mj_header endRefreshing];
                [_tableView.mj_footer endRefreshing];
                [_tableView reloadData];
                
            });
            
        } else {
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [_tableView.mj_header endRefreshing];
            [_tableView reloadData];
            
        });
        
        [_tableView reloadData];
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
    
}

-(void)callPhoneRequestFor:(NSString *)phoneStr{


    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",address_url,call_phone_api];
    NSDictionary * dic = @{@"UserTel":USER_DEFAULTGet(@"phone"),
                           @"AccountTel":phoneStr,
                           @"TelTime":str,
                           @"ver":md5ver};
           SHuiMBhubNoTimeLoding;
    [PostNetWorking postNetWorkingStr:parametersStr andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        
        if ([responseObject[@"state"] intValue]==1) {
            
            if (phoneStr.length>0) {
                NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",phoneStr];
                
                UIWebView * callWebview = [[UIWebView alloc] init];
                
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                
                [self.view addSubview:callWebview];
            }


        } 

    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];


}

@end
